
import * as express from 'express';
import * as path from 'path';
import * as http from 'http';
import { scannerDecoration, registerControllerToRouter} from '@jingli/restful';
import { JLRequest, JLResponse } from './types';
import { NextFunction, Request } from 'express-serve-static-core';

import { Response } from 'express';
import * as bodyParser from 'body-parser';
import { Express } from 'express';
//初始化错误语言包
import { init, JLError } from '@jingli/error';
import { authenticate } from './service/auth';
init({
    default: 'zh',
    langs: ['zh', 'en']
});

let app:Express = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const URL_PREFIX = '/api/v1';
const router = express.Router();
router.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.setHeader('Access-Control-Allow-Headers', '*');
    next();
});
router.use(authenticate);
//扫描注册路由
scannerDecoration(path.join(__dirname, 'controller'), [/\.d.ts$/]);
registerControllerToRouter(router, {
    isShowUrls: true,
});
router.use((err: Error, req: Request, res: Response, next: NextFunction) => { 
    if ((<JLError>err).code && (<JLError>err).msg) {
        return res.json(err);
    }
    next(err);
})

app.use(URL_PREFIX, router);

export { app };
export default app;